package com.example.backgroundmanager.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backgroundmanager.common.Result;
import com.example.backgroundmanager.entity.Comment;
import com.example.backgroundmanager.service.CommentService;
import com.example.backgroundmanager.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private CommentService commentService;



    @PostMapping
    public Result save(@RequestBody Comment comment) {
        if(comment.getId()==null){ //新增评论
            comment.setTime(DateUtil.now());
            comment.setUserId (TokenUtils.getCurrentUser().getId());
            if(comment.getPid()!=null){
                Integer pid=comment.getPid();
                Comment pComment=commentService.getById(pid);
                if(pComment.getOriginId()!=null){
                    comment.setOriginId(pComment.getOriginId());
                }else{
                    comment.setOriginId(comment.getPid());
                }
            }
        }
        return Result.success(commentService.saveOrUpdate(comment));
    }

    @PutMapping
    public Result update(@RequestBody Comment comment) {
        return Result.success(commentService.updateById(comment));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        commentService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id) {
        return Result.success(commentService.getById(id));
    }

    @GetMapping("/tree/{articleId}")
    public Result findtree(@PathVariable Integer articleId){
        //查询所有的评论和回复
        List<Comment> articleComments = commentService.findCommentDetail(articleId);
        //查询评论数据（不包括回复）
        List<Comment> originList=articleComments.stream().filter(comment->comment.getOriginId()==null).collect(Collectors.toList());
        //设置评论子节点。即回复内容
        for(Comment origin : originList){
            List<Comment> comments=articleComments.stream().filter(comment->origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            comments.forEach(comment ->{
                //找到当前父级用户的id和用户昵称，并且设置给当前的回复对象
                Optional<Comment> pComment= articleComments.stream().filter(c1 -> c1.getId().equals(comment.getPid())).findFirst();
                pComment.ifPresent((v->{
                    comment.setPUserId(v.getUserId());
                    comment.setPNickname(v.getNickname());
                }));
            });
            origin.setChildren(comments);
        }
        return Result.success(originList);
    }

    @GetMapping
    public Result findAll() {
        return Result.success(commentService.list());
    }

    @GetMapping("/page")
    public IPage<Comment> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize
//                                   @RequestParam(defaultValue = "") String content
                                   ){
        IPage<Comment> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Comment> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
//        if(!"".equals(content)){
//            queryWrapper.like("content",content);
//        }
        return commentService.page(page,queryWrapper);
    }


}

